package com.tju.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.*;
import com.tju.Result;
import com.tju.service.VodService;
import com.tju.serviceHandler.GuliException;
import com.tju.utils.ConstantUtils;
import com.tju.utils.InitObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;
    //上传视频
    @PostMapping("uploadVideo")
    public Result uploadVideo(MultipartFile file){
        //返回上传视频的id值
        String videoId = vodService.uploadVideo(file);
        return Result.ok().data("videoId",videoId);
    }

    //根据视频id删除阿里云视频
    @DeleteMapping("removeVideo/{id}")
    public Result removeVideo(@PathVariable String id){
        try {
            DefaultAcsClient client = InitObject.initVodClient(ConstantUtils.ACCESSKEY_ID, ConstantUtils.ACCESSKEY_SECRET);
            //创建删除视频的request
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(id);
            client.getAcsResponse(request);

            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除视频异常");
        }

    }

    //删除多个视频
    @DeleteMapping("delete-batch")
    public Result deleteBatch(@RequestParam("videoList") List<String> videoList){

        vodService.removeMoreVideo(videoList);
        return Result.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public Result getPlayAuth(@PathVariable String id){
        String accesskeyId = ConstantUtils.ACCESSKEY_ID;
        String accesskeySecret = ConstantUtils.ACCESSKEY_SECRET;

        System.out.println(accesskeyId);
        System.out.println(accesskeySecret);
        System.out.println("id = " + id);

        try {
            //创建初始化对象
            DefaultAcsClient cl = InitObject.initVodClient(accesskeyId,accesskeySecret);
            //创建获取视频地址request对象和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request对象设置视频id值
            request.setVideoId(id);

            GetVideoPlayAuthResponse response = cl.getAcsResponse(request);
            System.out.println(response.getPlayAuth());
            //获取视频播放凭证
            return Result.ok().data("playAuth",response.getPlayAuth());


        } catch (Exception  e) {
            e.printStackTrace();
            throw new GuliException(20001,"获取视频凭证失败");
        }

    }

}
